import {FileCacheCreateType, FileCacheType, FileCacheUpdateType} from "@/types/file-cache";
import getSqliteClient from "@/services/sqlite/init";

const client = getSqliteClient();

function mapToFileCache(row: any): FileCacheType {
  return {
    id: row.id,
    filePath: row.file_path,
    serverUrl: row.server_url,
    fileMd5: row.file_md5,
    fileType: row.file_type,
    fileSize: row.file_size,
    optional: row.optional ? JSON.parse(row.optional) : undefined,
    createTime: row.create_time,
  };
}

export async function createFileCache(
  cache: FileCacheCreateType
): Promise<void> {
  await client.runAsync(
    `INSERT INTO file_cache (file_path, server_url, file_md5, file_type,file_size, optional, create_time) VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [
      cache.filePath,
      cache.serverUrl,
      cache.fileMd5,
      cache.fileType,
      cache.fileSize,
      cache.optional ? JSON.stringify(cache.optional) : null,
      Date.now()
    ]
  );
}


export async function updateFileCacheServerUrlById(update: FileCacheUpdateType): Promise<void> {
    await client.runAsync(
        `UPDATE file_cache SET server_url = ? WHERE file_md5 = ?`,
        [update.serverUrl, update.fileMd5]
    );
}


export async function deleteFileCacheById(id: number): Promise<void> {
  await client.runAsync(`DELETE FROM file_cache WHERE id = ?`, [id]);
}

export async function getFileCacheByMd5(
  fileMd5: string
): Promise<FileCacheType | null> {
  const row = await client.getFirstAsync(
    `SELECT * FROM file_cache WHERE file_md5 = ?`,
    [fileMd5]
  );
  return row ? mapToFileCache(row) : null;
}

export async function clearFileCache(): Promise<void> {
  await client.runAsync(`DELETE FROM file_cache`);
}
